﻿using Core;
using UnityEngine;

/// <summary>
/// 围绕一个目标旋转
/// </summary>
public class CirclingMoveAgent : MoveAgent
{
    private float angle;
    private Vector3 pos = Vector3.zero;
    private TriggerRegion triggerRegion = new TriggerRegion();

    protected override void OnStart()
    {
        var forward = bullet.caster.Forward;
        var dir = (position - bullet.caster.Position).normalized;
        var normal = Vector3.Cross(forward, dir);
        angle = normal.y * Vector3.Angle(bullet.caster.Forward, (position - bullet.caster.Position).normalized);
    }

    void UpdateAngle()
    {
        angle = (angle + bullet.config.moveSpeed * Time.deltaTime) % 360;

        var x = bullet.config.rotateRadius * Mathf.Cos(angle);
        var z = bullet.config.rotateRadius * Mathf.Sin(angle);

        pos.Set(x, 0, z);
    }

    protected override Vector3 CalculateNewPosition()
    {
        UpdateAngle();

        return bullet.caster.Position + pos;
    }

    protected override BulletMoveStatus TryCollide(Vector3 oldPosition, Vector3 newPosition)
    {
        MoveResult.targets.Clear();

        var colliders = Physics.OverlapSphere(newPosition, bullet.config.collideSize, bullet.config.layerMask);
        triggerRegion.UpdateColliders(colliders, unit => unit == bullet.caster);
        MoveResult.targets.AddRange(triggerRegion.GetEnterUnit());

        MoveResult.hit = MoveResult.targets.Count > 0;

        return BulletMoveStatus.Move;
    }
}
